import socket, threading, CrazyProtocol, os
from tkinter import simpledialog
import time

SEVER_PORT = 30000


def read_send(s):
    while True:
        line = input('')
        if line is None or line == 'exit':
            break
        if ":" in line and line.startswith("//"):
            line = line[2:]
            s.send((CrazyProtocol.PRIVATE_ROUND + line.split(":")[0] + CrazyProtocol.SPLIT_SIGN +
                    line.split(":")[1] + CrazyProtocol.PRIVATE_ROUND).encode("utf-8"))
        else:
            s.send((CrazyProtocol.MSG_ROUND + line + CrazyProtocol.MSG_ROUND).encode('utf-8'))


s = socket.socket()
try:
    s.connect(("localhost", SEVER_PORT))
    tip = ""
    while True:
        user_name = input(tip + "输入用户名：\n")
        s.send((CrazyProtocol.USER_ROUND + user_name + CrazyProtocol.USER_ROUND).encode('utf-8'))
        time.sleep(0.2)
        result = s.recv(2048).decode('utf-8')
        if result is not None and result != '':
            if result == CrazyProtocol.NAME_REP:
                tip = '用户名重复'
                continue
            if result == CrazyProtocol.LOGIN_SUCCESS:
                break
except:
    print("网络异常，请重新登陆")
    s.close()
    os._exit(1)


def client_target(s):
    try:
        while True:
            line = s.recv(2048).decode('utf-8')
            if line is not None:
                print(line)
    finally:
        s.close()


threading.Thread(target=client_target, args=(s,)).start()
read_send(s)
